<template>
  <div class="delivery-home">
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon today-orders">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ todayStats.orderCount }}</div>
                <div class="stat-label">今日配送</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon today-earnings">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">¥{{ todayStats.totalEarnings }}</div>
                <div class="stat-label">今日收入</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon pending-orders">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ pendingOrdersCount }}</div>
                <div class="stat-label">待配送</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon completed-orders">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ completedOrdersCount }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <div class="content-section">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="pending-orders">
            <template #header>
              <div class="card-header">
                <span>待配送订单</span>
                <el-button text @click="$router.push('/delivery/orders')">
                  查看全部
                </el-button>
              </div>
            </template>
            
            <el-table :data="pendingOrders" style="width: 100%">
              <el-table-column prop="orderNumber" label="订单号" width="120" />
              <el-table-column prop="merchantName" label="商家" width="120" />
              <el-table-column prop="customerName" label="客户" width="100" />
              <el-table-column prop="deliveryAddress" label="配送地址" />
              <el-table-column prop="totalAmount" label="金额" width="100">
                <template #default="scope">
                  ¥{{ scope.row.totalAmount }}
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="下单时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button
                    type="primary"
                    size="small"
                    @click="acceptOrder(scope.row.id)"
                  >
                    接单
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <div v-if="pendingOrders.length === 0" class="empty-state">
              <el-empty description="暂无待配送订单" />
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="delivery-status">
            <template #header>
              <span>配送状态</span>
            </template>
            
            <div class="status-info">
              <div class="status-item">
                <span class="label">当前状态：</span>
                <el-tag :type="deliveryInfo?.status === 'ONLINE' ? 'success' : 'danger'">
                  {{ getStatusText(deliveryInfo?.status) }}
                </el-tag>
              </div>
              
              <div class="status-item">
                <span class="label">联系电话：</span>
                <span>{{ deliveryInfo?.phone || '未设置' }}</span>
              </div>
              
              <div class="status-item">
                <span class="label">配送区域：</span>
                <span>{{ deliveryInfo?.deliveryArea || '未设置' }}</span>
              </div>
              
              <div class="status-item">
                <span class="label">今日里程：</span>
                <span>{{ todayStats.totalDistance || 0 }}km</span>
              </div>
            </div>
            
            <div class="status-actions">
              <el-button
                type="primary"
                size="large"
                style="width: 100%; margin-bottom: 15px"
                @click="$router.push('/delivery/orders')"
              >
                <el-icon><Document /></el-icon>
                查看订单
              </el-button>
              
              <el-button
                type="success"
                size="large"
                style="width: 100%; margin-bottom: 15px"
                @click="$router.push('/delivery/profile')"
              >
                <el-icon><User /></el-icon>
                个人中心
              </el-button>
            </div>
          </el-card>
          
          <el-card class="recent-activity" style="margin-top: 20px">
            <template #header>
              <span>最近活动</span>
            </template>
            
            <div class="activity-list">
              <div
                v-for="activity in recentActivities"
                :key="activity.id"
                class="activity-item"
              >
                <div class="activity-icon">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="activity-content">
                  <div class="activity-title">{{ activity.title }}</div>
                  <div class="activity-time">{{ formatTime(activity.createdAt) }}</div>
                </div>
              </div>
              
              <div v-if="recentActivities.length === 0" class="empty-activity">
                暂无活动记录
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Document, Money, Clock, Check } from '@element-plus/icons-vue'
import { getDeliveryPersonInfo } from '../../api/delivery'
import { getPendingOrders, getTodayStats, acceptOrder as acceptOrderApi } from '../../api/order'
import dayjs from 'dayjs'

const router = useRouter()

const deliveryInfo = ref(null)
const pendingOrders = ref([])
const todayStats = ref({
  orderCount: 0,
  totalEarnings: 0,
  totalDistance: 0
})
const pendingOrdersCount = ref(0)
const completedOrdersCount = ref(0)
const recentActivities = ref([])

const getStatusText = (status) => {
  const statusMap = {
    'ONLINE': '在线',
    'OFFLINE': '离线',
    'BUSY': '忙碌'
  }
  return statusMap[status] || status
}

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const acceptOrder = async (orderId) => {
  try {
    await acceptOrderApi(orderId)
    ElMessage.success('接单成功')
    loadData()
  } catch (error) {
    ElMessage.error('接单失败')
  }
}

const loadData = async () => {
  try {
    // 加载配送员信息
    const deliveryResponse = await getDeliveryPersonInfo()
    deliveryInfo.value = deliveryResponse.data
    
    // 加载今日统计
    const statsResponse = await getTodayStats()
    todayStats.value = statsResponse.data
    
    // 加载待配送订单
    const ordersResponse = await getPendingOrders()
    pendingOrders.value = ordersResponse.data
    
    // 计算订单数量
    pendingOrdersCount.value = pendingOrders.value.length
    completedOrdersCount.value = todayStats.value.orderCount - pendingOrdersCount.value
    
    // 模拟最近活动数据
    recentActivities.value = [
      {
        id: 1,
        title: '完成订单 #20241201001',
        createdAt: new Date(Date.now() - 30 * 60 * 1000)
      },
      {
        id: 2,
        title: '接单 #20241201002',
        createdAt: new Date(Date.now() - 60 * 60 * 1000)
      },
      {
        id: 3,
        title: '上线开始工作',
        createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000)
      }
    ]
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.delivery-home {
  padding: 20px;
}

.stats-section {
  margin-bottom: 30px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.today-orders {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.today-earnings {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.pending-orders {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.completed-orders {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

.content-section {
  margin-top: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.status-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.label {
  color: #7f8c8d;
  font-size: 14px;
}

.status-actions {
  display: flex;
  flex-direction: column;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-size: 14px;
  color: #2c3e50;
  margin-bottom: 4px;
}

.activity-time {
  font-size: 12px;
  color: #7f8c8d;
}

.empty-activity {
  text-align: center;
  color: #7f8c8d;
  font-size: 14px;
  padding: 20px 0;
}
</style>
